﻿#include "once_trigger_thread.h"

void OnceTriggerADCThread::start()
{
  thread_is_running_ = true;

  auto base_device = base_device_.lock();
  total_data_length_ = base_device->GetCurrentDataLength();
  data_.reserve(total_data_length_);

  // 超时时间 = 数据长度 / 采样率
  timeout_msec_ = (static_cast<double>(total_data_length_) / base_device->GetCurrentSampleRate() * 1000) + 500;

  // 启动线程
  thread_ = std::thread(&OnceTriggerADCThread::run, this);
}

void OnceTriggerADCThread::quit()
{
  {
    std::lock_guard<std::mutex> lock(mutex_);
    thread_is_running_ = false;
  }
  cv_.notify_one();
  if (thread_.joinable())
  {
    thread_.join();
  }
}

void OnceTriggerADCThread::run()
{
  std::cout << "OnceTriggerADCThread start" << std::endl;
  auto base_device = base_device_.lock();

  while (thread_is_running_)
  {
    auto temp_data = std::make_unique<float[]>(total_data_length_);
    bool success = base_device->TryReadADCData(channel_, temp_data.get(), total_data_length_);

    if (!thread_is_running_)
    {
      break;
    }

    if (!success)
    {
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
      continue;
    }

    for (int j = 0; j < total_data_length_; j++)
    {
      data_.emplace_back(temp_data[j]);
    }
    std::cout << "channel " << channel_ + 1 << " data size: " << data_.size() << std::endl;

    if (!CheckDataEmpty())
    {
      // 获取到足够的数据后，清空多余的数据
      base_device->ClearDataBuffer(channel_);
      break;
    }
  }

  std::cout << "OnceTriggerADCThread end" << std::endl;
  thread_is_running_ = false;
}



bool OnceTriggerADCThread::CheckDataEmpty()
{
  return data_.empty();
}

void OnceTriggerADCThread::setThread_is_running(bool newThread_is_running)
{
    thread_is_running_ = newThread_is_running;
}

bool OnceTriggerADCThread::thread_is_running(){
  return thread_is_running_;
}
